package org.ls.petclinic.web;

import cn.hutool.core.util.ObjectUtil;
import org.ls.petclinic.dao.OwnerDao;
import org.ls.petclinic.dao.PetsDao;
import org.ls.petclinic.dao.VetSpecialtiesDao;
import org.ls.petclinic.dao.VetsDao;
import org.ls.petclinic.dao.impl.OwnerDaoImpl;
import org.ls.petclinic.dao.impl.PetsDaoImpl;
import org.ls.petclinic.dao.impl.VetSpecialtiesDaoImpl;
import org.ls.petclinic.dao.impl.VetsDaoImpl;
import org.ls.petclinic.pojo.Owner;
import org.ls.petclinic.pojo.Pets;
import org.ls.petclinic.untils.JdbcUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 浪矢先生
 * @description
 * @create 2022-12-05 23:47
 */
@WebServlet(urlPatterns = "/addPet")
public class AddPet extends BaseServlet{
    private PetsDao petsDao=new PetsDaoImpl();
    private OwnerDao ownerDao=new OwnerDaoImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");

        //请求参数
        //添加主人方式 0,已有中添加 1,新添加
        String type1 = req.getParameter("type");
        int type = 0;
        String pName = req.getParameter("pName");
        String birthDate = req.getParameter("birthDate");
        Long typeId = Long.parseLong(req.getParameter("typeId"));
        int result=0;
        if (ObjectUtil.isNull(type1)){
            long id = Long.parseLong(req.getParameter("id"));
           result += petsDao.add(new Pets(null,pName,birthDate, id,typeId));
        }else {
             type = Integer.parseInt(type1);
            if (type==0){
                Long ownerId = Long.parseLong(req.getParameter("OwnerId"));
                result +=  petsDao.add(new Pets(null,pName,birthDate,ownerId,typeId));
            } else if (type==1) {

                Long id = (long) ownerDao.add(new Owner(null,
                        req.getParameter("oName"),
                        req.getParameter("address"),
                        req.getParameter("city"),
                        req.getParameter("oPhone")));
                result +=  petsDao.add(new Pets(null,pName,birthDate,id,typeId));
            }
        }

        JdbcUtils.commitAndClose();
        if (result>0){
            req.setAttribute("msg", "添加宠物成功!");
        }else {
            req.setAttribute("msg", "添加宠物失败!");
        }
        //页面转发
        req.getRequestDispatcher("/jsp/getPets.jsp").forward(req, resp);
//        resp.sendRedirect(req.getContextPath() + "/jsp/getUnHealthyPet.jsp");
    }
}
